<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/

if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
    require __DIR__.'/../storage/framework/maintenance.php';
}

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

require __DIR__.'/../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$http = new \Swoole\Http\Server("0.0.0.0", 9501);

$http->on('request', function ($swooleRequest, $swooleResponse) use ($kernel) {
    $swooleResponse->header('Content-type', 'text/html; charset=utf-8', true);

    $_SERVER = [];
    if (isset($swooleRequest->server)) {
        foreach ($swooleRequest->server as $k => $v) {
            $_SERVER[strtoupper($k)] = $v;
        }
    }
    // 这个一定要写不然会报错
    $_SERVER['argv'] = [];
    if (isset($swooleRequest->header)) {
        foreach ($swooleRequest->server as $k => $v) {
            $_SERVER[strtoupper($k)] = $v;
        }
    }
    $_GET = [];
    if (isset($swooleRequest->get)) {
        foreach ($swooleRequest->get as $k => $v) {
            if($k == 's'){
                $_GET[$k] = $v;
            }else{
                $_GET[strtoupper($k)] = $v;
            }
        }
    }
    $_POST =[];
    if (isset($swooleRequest->post)) {
        foreach ($swooleRequest->post as $k => $v) {
            $_POST[strtoupper($k)] = $v;
        }
    }

    $response = tap($kernel->handle(
        $request = Request::capture()
    ))->getContent();

    $swooleResponse->end($response->getContent());

    $kernel->terminate($request, $response);
});

$http->start();

